<template>
  <div>
    <div>
      <a-button type="primary" @click="showModal">咨询客服</a-button>

      <div>
        <a-modal v-model="visible" title="选择客服" @ok="handleOk">
          <p v-for="i in userlist" @click="showModal1(i.id)" v-if="uid!=i.id">
            {{ i.username }}
          </p>
        </a-modal>
      </div>

      <a-modal v-model="visible1" title="聊天" @ok="handleOk1" width="40%">
        <a v-for="j in listz">
          <p v-if="j.send == uid" style="text-align: right">{{ j.name }}</p>
          <p v-else>{{ j.uname }}: {{ j.name }}</p>
        </a>
        <a-input id="chat-message-input" v-model="info" type="text"></a-input>
        <a-button type="primary" @click="sendmessage">
          发送
        </a-button>
      </a-modal>

    </div>
  </div>
</template>

<script>
export default {
  name: "socket",
  data() {
    return {
      info: '',
      listz: [],
      visible: false,
      userlist: [],
      visible1: false,
      user_id: '',
      uid: localStorage.getItem('uid'),
      socket:'',
    }
  },
  methods: {
    showModal() {
      this.visible = true;
    },
    handleOk(e) {
      console.log(e);
      this.visible = false;
    },
    showModal1(id) {
      this.visible1 = true;
      this.user_id = id
      var _this = this
      this.socket = new WebSocket(`ws:127.0.0.1:8000/z/service/${id}/${this.uid}/`)
      this.socket.onmessage = function (e) {
        _this.listz = JSON.parse(e.data)
      };
      // if (socket.readyState == WebSocket.OPEN) {
      //   socket.onopen();
      // }
    },
    handleOk1(e) {
      // console.log(e);
      this.socket.close()
      this.visible1 = false
      this.user_id = ""
      this.listz = []
    },
    sendmessage() {
      this.$axios({
        url: 'http://127.0.0.1:8000/z/addmessage/',
        method: 'post',
        data: {'send': this.uid, 'reception': this.user_id, 'name': this.info}
      }).then(res => {
        console.log(res.data)
        if(res.data.msg=='发送成功'){
          this.info = ""
        }
      })
    },
  },
  created() {
    this.$axios({
      url: 'http://127.0.0.1:8000/z/user/'
    }).then(res => {
      console.log(res.data)
      this.userlist = res.data.data
    })
  }
}
</script>

<style scoped>

</style>
